package cn.ybz21.hibot.resource;

import java.util.List;

import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import cn.ybz21.hibot.bean.Robot;
import cn.ybz21.hibot.bean.Node;
import cn.ybz21.hibot.bean.ResultCode;
import cn.ybz21.hibot.dao.ClientDAO;
import cn.ybz21.hibot.util.MQTTPublisher;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

@Path("/node")
public class NodeResource {
	/**
	 * 
	 * 
	 * 客户端向机器人上传node信息
	 * @param data
	 * @return
	 */
	@POST
	@Path("/uploadNodeList")
	@Produces(MediaType.APPLICATION_JSON)
	public ResultCode uploadNodeList(@FormParam(value = "data") String data) {
		Gson gson = new Gson();
		System.out.println("data:" + data);
		List<Node> nodes = gson.fromJson(data, new TypeToken<List<Node>>() {
		}.getType());
		System.out.println("data:" + data);
		save2DB(nodes);
		ResultCode rCode = new ResultCode();
		return rCode;
	}
	/**
	 * 
	 * @param data
	 * @return
	 */
	@POST
	@Path("/uploadNodeInfo")
	@Produces(MediaType.APPLICATION_JSON)
	public ResultCode publishNodeInfo(@FormParam(value = "data") String data) {
		Gson gson = new Gson();
		System.out.println("publishNodeInfo data:" + data);

		ResultCode rCode = new ResultCode();
		return rCode;
	}
	/**
	 * 向客户端推送1
	 * <p>http://127.0.0.1:8080/HiBotServer/api/v1/node/publish/clientIdMac/1 </p>
	 * @param idMac
	 * @return
	 */
	@GET
	@Path("/publish/clientIdMac/{idMac}")
	@Produces(MediaType.APPLICATION_JSON)
	public ResultCode publishTask(@PathParam("idMac") String idMac) {
		ResultCode rCode = new ResultCode();
		MQTTPublisher.postMessage("getTaskList/" + idMac, "");
		return rCode;
	}
	/**
	 * 向客户端推送2
	 * <p>http://127.0.0.1:8080/HiBotServer/api/v1/node/publish/clientId/1 </p>
	 * @param idMac
	 * @return
	 */
	@GET
	@Path("/publish/clientId/{id}")
	@Produces(MediaType.APPLICATION_JSON)
	public ResultCode publishTaskById(@PathParam("id") String id) {
		ResultCode rCode = new ResultCode();
		MQTTPublisher.postMessage("getTaskList/" + id, "");
		return rCode;
	}
	/**
	 * 获取客户端的节点详情
	 * <p>
	 * http://127.0.0.1:8080/HiBotServer/api/v1/node/clientId/1
	 * </p>
	 * @param id
	 * @return
	 */
	@GET
	@Path("/clientId/{id}")
	@Produces(MediaType.APPLICATION_JSON)
	public List<Node> getNodesByClientId(@PathParam("id") String id) {
		System.out.println("aaa");
		List<Node> nodes = new ClientDAO().queryClientById(id).nodes;
		return nodes;
	}

	/**
	 * 数据持久化
	 * 
	 * @param nodes
	 */
	private void save2DB(List<Node> nodes) {
		if (nodes.size() > 0) {
			String idmac = nodes.get(0).clientIdMac;
			ClientDAO dao = new ClientDAO();
			Robot client = dao.queryClientByIdMac(idmac);
			client.nodes = nodes;
			dao.updateClient(client);
		}
	}

}